//
//  SecurityStatisticsTopVC.swift
//  SBSafetyApp
//
//  Created by Lina on 2023/5/19.
//
// 【首页-保安管理】保安履职情况

import Foundation
import UIKit

class SecurityStatisticsTopVC: SubLevelViewController, PullToRefreshPresentable {
    
    let header = SecurityStatisticsTopHeaderView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 420))
    
    var datas: [BaglSignInfoModel?] = []
    
    var param =  SecurityParam()
    
    var pageNum: Int = 1
    var totalPage: Int64 = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        view.backgroundColor = .bg
        navigationController?.navBarStyle(.white)
        setupUI()
        setupPullToRefresh(on: tableView)

        if deptName == nil {
            deptName = BSUser.currentUser.deptName
            deptId = BSUser.currentUser.deptId
        }
        
        title = deptName ?? "保安管理"
        
        param.deptId = deptId
        param.date = date
        param.dateType = dateEnum.rawValue
        param.pageSize = PageSize

        reloadData()
    }
    
    deinit {
        tableView.removeAllPullToRefresh()
    }
    
    func reloadAction() {
        pageNum = 1
        getList()
    }
    
    func loadAction() {
        if pageNum >= totalPage {
            return
        }
        pageNum += 1
        getList()
    }
    
    func reloadData() {
        view.showToastActivity()
        // 履职情况
        API.getBaglBalzByDept(withParam: param) { responseModel in
            if responseModel.errorCode == .Success {
                DispatchQueue.main.async {
                    self.header.managerPanel.buildWDList(responseModel.model?.wdList ?? [])
                    self.header.managerPanel.buildData(responseModel.model?.zwcl ?? "0.0")
                    self.view.hideToastActivity()
                }
            }
        }
        
        // 各任务完成情况
        API.getBaglRwwcqk(withParam: param) { responseModel in
            if responseModel.errorCode == .Success {
                DispatchQueue.main.async {
                    let ms = responseModel.models ?? []
                    self.header.taskPanel.buildWDList(ms)
                    self.header.frame = CGRect(x: 0, y: 0, width: ScreenWidth, height: 340.0 + CGFloat(ms.count) * 70)
                    self.tableView.reloadData()
                }
            }
        }
        
        // 当日考勤记录
        pageNum = 1
        getList()
    }
    
    func getList() {
        param.pageNum = pageNum
        
        // 当日考勤记录
        API.getBaglSignInfo(withParam: param) { responseModel in
            if responseModel.errorCode == .Success {
                if self.pageNum > 1 && (responseModel.models == nil || responseModel.models?.count == 0) {
                    self.pageNum -= 1
                    return
                }
                if self.pageNum == 1 {
                    self.datas.removeAll()
                }
                self.totalPage = responseModel.totalPage
                self.datas.append(contentsOf: responseModel.models ?? [])
                DispatchQueue.main.async {
//                    self.tableView.tableShowEmpty(withDataCount: self.datas.count)
                    self.tableView.reloadData()
                }
            }
        }
    }

    // MARK: - Setup

    func setupUI() {
        view.backgroundColor = .bg
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.top.equalTo(view.safeAreaLayoutGuide.snp.top)
            make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            make.left.equalToSuperview().offset(10)
            make.right.equalToSuperview().offset(-10)
        }
        
        header.managerPanel.delegate = self
        header.taskPanel.delegate = self
        tableView.tableHeaderView = header
    }
    
    lazy var tableView: UITableView = {
        let v = UITableView()
        v.dataSource = self
        v.delegate = self
        v.separatorStyle = .none
        v.layer.cornerRadius = 10
        v.layer.masksToBounds = true
        v.backgroundColor = .bg
        v.register(SecurityAttendanceCell.self, forCellReuseIdentifier: "SecurityAttendanceCell")
        return v
    }()
}

extension SecurityStatisticsTopVC: UITableViewDataSource, UITableViewDelegate {

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return datas.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let data = datas[indexPath.row]
        let cell = (tableView.dequeueReusableCell(withIdentifier: "SecurityAttendanceCell", for: indexPath)) as! SecurityAttendanceCell
        cell.selectionStyle = .none
        cell.reload(withData: data)
        return cell
    }

    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 70
    }

    public func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.row == datas.count - 1 {
            tableView.setCornerRadiusSectionBottom(willDisplay: cell, forRowAt: indexPath)
        }
    }
}

extension SecurityStatisticsTopVC: SecurityManagerPanelDelegate {
    func didTapDetailButton() {
        let appvc = SecurityPersonStatisticsVC(withDeptId: deptId, deptName: deptName, date: date, dateEnum: dateEnum)
        navigationController?.pushViewController(appvc, animated: true)
    }

    func didSelected(year: Int, quarter: Int?, month: Int?, day: Int?, dateEnum: CustomDateEnum) {
        let m = month ?? 1
        let d = day ?? 1
        
        self.date = "\(year)-\(m < 10 ? "0\(m)" : "\(m)")-\(d < 10 ? "0\(d)" : "\(d)")"
        self.dateEnum = dateEnum

        reloadData()
    }
}

extension SecurityStatisticsTopVC: SecurityTaskPanelDelegate {
    func handleTaskSelected(_ model: BaglRwwcqkModel) {
        if let id = model.taskId {
            let appvc = SecurityTaskProgressVC(withDeptId: deptId, deptName: deptName, date: date, dateEnum: dateEnum, rwid: String(id))
            navigationController?.pushViewController(appvc, animated: true)
        }
        
    }
}
